#include <queue>
using namespace std;

class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};

/*
 * @lc app=leetcode.cn id=117 lang=cpp
 *
 * [117] 填充每个节点的下一个右侧节点指针 II
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        Node* res = root, *temp = nullptr, *last = nullptr;
        while (root) {
            if (root->left) {
                if (!temp) temp = root->left;
                if (last) last->next = root->left;
                root->left->next = root->right, last = root->left;  
            }
            if (root->right) {
                if (!temp) temp = root->right;
                if (last) last->next = root->right;
                if (root->next) root->right->next = root->next->left, last = root->right;
            }
            if (root->next) root = root->next;
            else root = temp, temp = nullptr, last = nullptr;
        }
        return res;
    }
};
// @lc code=end

